# -*- coding: utf-8 -*-
"""
summary:
    关于Views的一些常用方法
author:
    李华顺<huacnlee@gmail.com>
"""
import traceback
from django.http import HttpResponse,Http404, HttpResponseRedirect, HttpResponseServerError
from django.shortcuts import render_to_response
from django.template import Context, loader,RequestContext
from django.http import Http404
from utils import logs
from utils.helper import convert
from utils.components import ExecuteState

def render_template(template):
    """
    summary:
        允许views里面直接通过返回来调用template <http://huacn.blogbus.com/logs/31300003.html>
    """
    def renderer(func):
		def wapper(request,*args,**kw):
			output = func(request,*args,**kw)
			if not isinstance(output,dict):
				return output
			return out_page(template,output)
		return wapper
    return renderer	
			

def out_page(template,data):
    """
    summary:
        输出页面HTML,template的Response
    params:
        filename    template 文件名
        data    Context 的数据字典
    author:
    李华顺<huacnlee@gmail.com>
	"""
    _template = loader.get_template(template)
    _context = Context(data)
    _output = _template.render(_context)
    return HttpResponse(_output)

def out_html(template,data):
    """
    summary:
        输出HTML代码，来自template的
    params:
        filename    template 文件名
        data    Context 的数据字典
    author:
        李华顺<huacnlee@gmail.com>
    """
    return render_to_response(template,data).content

def out_text(content):
    """
    summary:
        输入纯文本代码
    params:
        content    要输出的内容
    author:
        李华顺<huacnlee@gmail.com>
    """
    return HttpResponse(content)

def out_404():
    """
    summary:
        返回404结果
    author:
        李华顺 <huacnlee@gmail.com>
    """
    return out_page("404.html", None)

def out_message(state):
    """
    summary:
        显示错误/或成功提示页面
    author:
        李华顺 <huacnlee@gmail.com>
    """
    template = "message.html"
    return out_page(template,state)

def out_unknow_error():
    """
    summary:
        显示未定义错误
    author:
        李华顺 <huacnlee@gmail.com>
    """
    state = ExecuteState()
    state.message = "服务器暂时无法响应此请求，请稍候在试。"
    state.success = False
    return out_message(state)


def get_form_val(request,key,default=''):
    """
    summary:
        取得request.POST的值,并可给定没有内容时的默认值,用它将不会出错
    params:
        request    http request 对象
        key        键值
        default    没有内容时的默认值
    author:
        李华顺 <huacnlee@gmail.com>
    """
    if type(request) == type(''):
        raise "get_form_val 方法有笔误，未传送request对象."
    try:
        return request.POST[key]
    except:
        return default

def get_session_val(request,key,default=''):
    """
    summary:
        取得request.session 的值
    params:
        request    http request 对象
        key        session key
        default    默认值
    author:
        李华顺 <huacnlee@gmail.com>
    """
    if type(request) == type(''):
        raise "get_session_val 方法有笔误，未传送request对象."
    try:
        return request.session[key]
    except:
        return default

def set_session_val(request,key,val):
    """
    summary:
        设置session的值
    params:
        request    http request 对象
        key        session key
        val    值
    author:
        李华顺 <huacnlee@gmail.com>
    """
    request.session[key] = val

def get_query_val(request,key,default=''):
    """
    summary:
        取得request.GET的值,并可给定没有内容时的默认值,用它将不会出错
    params:
        request    http request 对象
        key        键值
        default    没有内容时的默认值
    author:
        李华顺<huacnlee@gmail.com>
    """
    if type(request) == type(''):
        raise "get_query_val 方法有笔误，未传送request对象."
    try:
        return request.GET[key]
    except:
        return default

    

# #####################
# 以下是用户信息的助手
# #####################
def is_logined(request):
    """
    summary:
        检查是否已经登录
    params:
        request    页面request
    returns:
        Boolean
    author:
        李华顺<huacnlee@gmail.com>
    """
    if get_session_val(request,"user_logined",'') == "1":
        return True
    else:
        return False

def get_current_user_id(request):
    """
    summary:
        取得当前登录的用户编号
    """
    return convert.to_int(get_session_val(request,'user_id',''))


def login_save(request,user = None):
    """
    summary:
        登录,保存登录信息
    params:
        request   页面request
        user        User用户信息
    author:
        李华顺<huacnlee@gmail.com>
    """
    if user != None:
        set_session_val(request, 'user_logined', '1')
        set_session_val(request, 'user_id', user.id)

def login_out(request):
    """
    summary:
        登出
    params:
        request   页面request
    author:
        李华顺<huacnlee@gmail.com>
    """
    set_session_val(request, 'user_logined', '')
    set_session_val(request, 'user_id', '')
